//用户路由
const express = require("express");
const router = express();
const User = require("../model/User");
const { code } = require("../config/key");
const loginService = require("../service/loginService");
const registerService = require("../service/registerService");

//登录-客户端
router.post("/login", async(req, res, next) => {
    try {
        const data = await loginService.findOne(req.body);
        res.status(data.status).json(data)
    } catch (err) {
        return next(err);
    }
});

//人员详情信息
router.get('/detail/:id', async(req, res) => {
    const data = await User.findById(req.params.id)
    res.send({
        status: "ok",
        data: data,
    })
})

//人员信息修改+重置密码
router.put('/update/:id', async(req, res) => {
    console.log(req.body,req.params,555)
    if (req.body.password) {
        req.body.password = code(req.body.password);
    }
    const data =  await User.findByIdAndUpdate(req.params.id, req.body,{ new: true })
    res.send({
        status: "ok",
        data : data,
    })
})

//添加人员
router.post("/register", async(req, res, next) => {
    try {
        const data = await registerService.findOne(req.body);
        res.status(data.status).json(data)
    } catch (err) {
        return next(err);
    }
});

//分页查询列表+姓名+学号模糊查询:
router.get('/list', async(req, res) => {
    console.log(req.query)
    page = parseInt(req.query.page);
    limit = parseInt(req.query.limit);  
    const total = await User.countDocuments({nickname:{$regex: req.query.nickname,$options: 'i'},username:{$regex: req.query.username}})
    const data = await User.find({nickname:{$regex: req.query.nickname,$options: 'i'},username:{$regex: req.query.username}}).skip((page - 1) * limit).limit(limit) 
    res.send({
        status: "ok",
        data: data,total
    })
})

//删除人员
router.delete('/delete/:id', async(req, res) => {
    await User.findByIdAndDelete(req.params.id)
    res.send({
        status: "ok"
    })
})

//以下为测试接口

//根据学号精确查询人员
router.get('/findByUsername/:username', async(req, res) => {
    const data = await User.find({ 'username': req.params.username })
    res.send({
        status: "ok",
        data: data,
    })
})

//全部人员信息
router.get('/listuser', async(req, res) => {
    const data = await User.find()
    res.send({
        status: "ok",
        data: data,
    })
})

//删库
router.post('/test', async(req, res) => {
    console.log(req.body)
    await User.deleteMany();
    res.send({
        status: "ok",
    })
})

module.exports = router;